package com.zb;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ThreadPoolUtils {
    private static volatile ThreadPoolFactory threadPoolFactory;

    private ThreadPoolUtils() {
        throw new AssertionError("工具类不允许实例化");
    }

    static void init(ThreadPoolFactory factory) {
        if (threadPoolFactory == null) {
            synchronized (ThreadPoolUtils.class) {
                if (threadPoolFactory == null) {
                    threadPoolFactory = factory;
                }
            }
        }
    }

    // 静态工具方法：执行任务
    public static void execute(String threadPoolName, Runnable task) {
        getExecutor(threadPoolName).execute(task);
    }

    public static <T> Future<T> submit(String threadPoolName, Callable<T> task) {
        return getExecutor(threadPoolName).submit(task);
    }

    public static void executeWithTimeout(String threadPoolName, Runnable task, long timeout, TimeUnit unit)
            throws TimeoutException, InterruptedException {
        Future<?> future = getExecutor(threadPoolName).submit(task);
        try {
            future.get(timeout, unit);
        } catch (TimeoutException e) {
            future.cancel(true);
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("任务执行失败", e);
        }
    }

    // 获取线程池（校验初始化状态）
    private static ExecutorService getExecutor(String threadPoolName) {
        if (threadPoolFactory == null) {
            throw new IllegalStateException("线程池工厂未初始化，请检查Spring配置");
        }
        return threadPoolFactory.build(threadPoolName);
    }
}